<?php
/**
 * Created by PhpStorm.
 * User: lzy
 * Date: 2018/11/7
 * Time: 9:51
 */

namespace App\FreeBird\Repositories;


use App\FreeBird\Contracts\StoreInterface;
use App\FreeBird\Models\StoreModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class  DbStoreRepositories implements StoreInterface
{

    /**
     * 商店名称
     * @return StoreModel
     */
    public function getStoreModel()
    {
        return app()->make(StoreModel::class);
    }

    /**
     * 数据列表
     * @param $where
     * @return mixed|void
     */
    public function getList($where)
    {
        $request = Request::instance();
        $limit = empty($request->input("limit")) ? 10 : $request->input("limit");
        return $this->getStoreModel()->newQuery()->where($where)->orderBy("create_time", "desc")->paginate($limit);
    }

    public function getListJili($where,$data){
        $request = Request::instance();
        $limit = empty($request->input("limit")) ? 10 : $request->input("limit");
        $lon=$data['lng'];
        $lat=$data['lat'];
        return $this->getStoreModel()->newQuery()->select(["id","stroe_name","class","class_name","country","city","region","latitude","longitude","addr","remark",DB::raw("ROUND(
        6378.138 * 2 * ASIN(
            SQRT(
                POW(
                    SIN(
                        (
                           ".$lat." * PI() / 180 - latitude * PI() / 180
                        ) / 2
                    ),
                    2
                ) + COS(".$lat." * PI() / 180) * COS(latitude * PI() / 180) * POW(
                    SIN(
                        (
                            ".$lon." * PI() / 180 - longitude * PI() / 180
                        ) / 2
                    ),
                    2
                )
            )
        ) * 1000
    ) AS juli")])->where($where)->orderBy("juli", "desc")->paginate($limit);
    }

    /**
     * 保存数据
     * @param $data
     * @return mixed|void
     */
    public function saveData($data)
    {
        return $this->getStoreModel()->newQuery()->updateOrCreate(["id" => $data['id']], $data);
    }

    /**
     * 获取门店单条数据
     * @param $where
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|mixed|null|object
     */
    public function getInfo($where)
    {
        return $this->getStoreModel()->newQuery()->where($where)->first();
    }


    /**
     * 删除数据
     * @param $where
     * @return mixed
     */
    public function deleteData($where){
        return $this->getStoreModel()->newQuery()->where($where)->delete();
    }

    /**
     * 新增数据前台
     * @param $data
     * @return mixed|void
     */
    public function setStoreInfo($data)
    {
        if (empty($data['id'])) {
            $data['id'] = 0;
        }
        $data["uid"] = AUID;
        return $this->saveData($data);
    }
}